package nancal.mp.web.sys


import io.swagger.annotations.Api
import nancal.mp.db.mongo.entity.admin.*
import nancal.mp.db.mongo.mor
import nbcp.base.annotation.*
import nbcp.base.comm.ApiResult
import nbcp.base.comm.JsonResult
import nbcp.base.comm.ListResult
import nbcp.base.comm.PagerModel
import nbcp.base.extend.*
import nbcp.base.json.*
import nbcp.base.utils.Md5Util
import nbcp.myoql.db.mongo.query
import nbcp.myoql.db.mongo.queryById
import org.bson.Document
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController

/**
 * Created by yuxh on 2018/9/27
 */
@Api(tags = arrayOf("人员"))
@RestController
@RequestMapping("/admin-user")
class AdminUserController {
    @PostMapping("/list")
    fun list_user(
        name: String, mobile: String,
        @org.springframework.web.bind.annotation.RequestBody query: PagerModel<Any?>
    ): ListResult<Document> {
        var data = mor.admin.adminUser.query()
            .where { it.loginName mongoNotEquals "admin" }

        if (name.HasValue) {
            data.where { it.name mongoLike name }
        }

        if (mobile.HasValue) {
            data.where { it.mobile mongoLike mobile }
        }

//        if (isChecker.HasValue) {
//            data.where { it.isChecker match_equal isChecker.AsBoolean() }
//        }
//
//        if (isManager.HasValue) {
//            data.where { it.isManager match_equal isManager.AsBoolean() }
//        }
        data.orderByDesc { it.id }
            .withPager(query)

        return data.toMapListResult()
    }

    @PostMapping("/detail/{id}")
    fun detail(@Require id: String): ApiResult<AdminUser> {
        mor.admin.adminUser.queryById(id).toEntity()
            .apply {
                return ApiResult.of(this)
            }
    }


    @PostMapping("/resetPassword")
    fun forgetPassword(userId: String): JsonResult {
        var defaultPassword = Md5Util.getBase64Md5("12345678");
        mor.admin.adminLoginUser.updateById(userId)
            .set { it.password to defaultPassword }
            .exec()

        if (mor.affectRowCount > 0) {
            return JsonResult();
        } else return JsonResult.error("重置用户密码失败")
    }
}
